/**
 * @file yuv6.c
 * @author your name (you@domain.com)
 * @brief  灰阶数量barnum确定每一个灰度条中像素的亮度分量Y的取值。另一方面还要根据图像的宽度width和图像的高度height以及灰阶数量barnum确定每一个灰度条的宽度。
 * @version 0.1
 * @date 2021-04-27
 * 
 * @copyright Copyright (c) 2021
 * 
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

int simplest_yuv420_graybar(int width, int height, int ymin, int ymax, int barnum, char *url_out);

int main(void)
{
    simplest_yuv420_graybar(640, 360, 0, 255, 40, "graybar_640x360.yuv");
    return 0;
}

/**
 * Generate YUV420P gray scale bar.
 * @param width    Width of Output YUV file.
 * @param height   Height of Output YUV file.
 * @param ymin     Max value of Y
 * @param ymax     Min value of Y
 * @param barnum   Number of bars
 * @param url_out  Location of Output YUV file.
 */
int simplest_yuv420_graybar(int width, int height, int ymin, int ymax, int barnum, char *url_out)
{
    int barwidth;
    float lum_inc;
    uint8_t lum_temp;
    int uv_width, uv_height;
    FILE *fp = NULL;
    uint8_t *data_y = NULL;
    uint8_t *data_u = NULL;
    uint8_t *data_v = NULL;
    int t = 0, i = 0, j = 0;

    barwidth = width / barnum;
    lum_inc = (ymax - ymin) / (float)(barnum - 1);
    uv_width = width / 2;
    uv_height = height / 2;

    data_y = (uint8_t *)malloc(width * height);
    data_u = (uint8_t *)malloc(uv_width * uv_height);
    data_v = (uint8_t *)malloc(uv_width * uv_height);

    fp = fopen(url_out, "wb+");
    if (fp == NULL)
    {
        printf("fopen[%s]\n", strerror(errno));
        return -1;
    }

    printf("Y value from picture's left to right :\n");
    for (t = 0; t < (width / barwidth); t++)
    {
        lum_temp = ymin + (char)(t * lum_inc);
        printf("%3d \n", lum_temp);
    }

    for (j = 0; j < height; j++)
    {
        for (i = 0; i < width; i++)
        {
            t = i / barwidth;
            lum_temp = ymin + (char)(t * lum_inc);
            data_y[j * width + i] = lum_temp;
        }
    }

    for (j = 0; j < uv_height; j++)
    {
        for (i = 0; i < uv_width; i++)
        {
            data_u[j * uv_width + i] = 128;
        }
    }

    for (j = 0; j < uv_height; j++)
    {
        for (i = 0; i < uv_width; i++)
        {
            // data_v[j * uv_width + i] = 128;
            data_v[j * uv_width + i] = j*i % 128;
        }
    }

    fwrite(data_y, width *height, 1, fp);
    fwrite(data_u, uv_width * uv_height, 1, fp);
    fwrite(data_v, uv_width* uv_height, 1, fp);

    fclose(fp);

    free(data_y);
    free(data_u);
    free(data_v);

    return 0;
}